<template>
	<view class="device" v-if="userStore.hasToken && userStore.userInfo.register_method != 1">
		<view class="header">
			<Tabs :tabs="tabOptions" v-model="tabCurrent" @change="onTabChange" />
			<!-- <Filter :tab-current="tabCurrent" :actions="allActions" @confirm="handleFilterConfirm" /> -->
		</view>

		<view v-if="equipmentList.length" class="list">
			<view v-for="i of equipmentList" :key="i.id" class="equipment" hover-class="hover-default" @click="onClickEquipment(i)">
				<image class="cover-image" src="https://aed-mini.oss-cn-beijing.aliyuncs.com/cc75f394b1d4a2b9/12c5fcde07dcb306.png" mode="aspectFit" />
				<view class="cont flex flex-col flex-grow justify-evenly">
					<view class="flex-row">
						<view class="serial-number">{{ i.host_serial_no }}</view>
						<view v-if="i.showStatus" :class="['run-status', i.statusCode]">{{ i.statusText }}</view>
					</view>
					<view class="use-status">
						<template v-if="!i.showStatus">安装员：{{ i.installer_name || '无' }}</template>
						<template v-else>使用状态：{{ i.use_state == 0 ? '空闲' : '使用中' }}</template>
					</view>
					<view class="address flex justify-between">
						<template v-if="!i.showStatus">所属组织：{{ i.organization_name || '无' }}</template>
						<template v-else>
							<view class="text">{{ i.region }}{{ i.address }}</view>
							<image class="nav-icon" src="/static/nav.png" hover-stop-propagation @click.stop="tapNavMap(i)" />
						</template>
					</view>
				</view>
			</view>
			<uni-load-more :status="loadMoreStatus" />
		</view>
		<view v-else class="no-data">暂无数据</view>
		<view style="height: 118rpx"></view>
		<!-- 超级管理员、设备巡检员 -->
		<button
			v-if="userStore.userInfo.authorize == 5 || ([0, 1].includes(userStore.userInfo.authorize) && tabCurrent === 1)"
			class="btn-primary fixed-bottom"
			@click="scanQRCode('patrolInspection')"
		>
			扫码巡检
		</button>
		<!-- 超级管理员、设备安装员 -->
		<button
			v-if="userStore.userInfo.authorize == 6 || ([0, 1].includes(userStore.userInfo.authorize) && tabCurrent === 0)"
			class="btn-primary fixed-bottom"
			@click="scanQRCode('install')"
		>
			扫码安装
		</button>
	</view>
	<view v-else class="no-auth">
		<image class="no-auth__icon" src="/static/management/no-auth.png" />
		<view class="no-auth__label">暂无权限，请联系管理员</view>
	</view>
</template>

<script setup>
import { ref, reactive } from 'vue';
import { onShow, onReachBottom } from '@dcloudio/uni-app';
import { fetchEquipmentList, postNav,valUserDevice } from '@/api';
import { useUserStore } from '@/store/user';
import { getURLQuery } from '@/utils';
import Tabs from '@/components/Tabs/index.vue';
import Filter from './components/Filter.vue';

const userStore = useUserStore();
const tabCurrent = ref(0);
const equipmentList = ref([]);
const tabOptions = ref([]);
const query = ref({
	page: 1,
	limit: 10
});
const loadMoreStatus = ref('more');
const allActions = reactive({
	installer: [],
	inspector: [],
	superAdmin: [
		{ id: 0, name: '设备安装', key: 'type' },
		{ id: 1, name: '设备巡检', key: 'patrol_state' }
	]
});

onShow(() => {
	if (userStore.hasToken && userStore.userInfo.register_method != 1) {
		if (!(query.value.hasOwnProperty('type') || query.value.hasOwnProperty('patrol_state'))) initQuery();
		getData();
	}
});

onReachBottom(() => {
	if (loadMoreStatus.value === 'more') {
		query.value.page++;
		getData();
	}
});

/**
 * @param {string} imgStr
 * @return {string[]}
 */
function getCoverImages(imgStr) {
	return imgStr?.split('|') || [''];
}

function tapNavMap(i) {
	postNav({
		latitude: +i.latitude,
		longitude: +i.longitude,
		region: i.region,
		address: i.address,
		host_serial_no: i.host_serial_no
	});
	uni.openLocation({
		address: i.region + i.address,
		latitude: +i.latitude,
		longitude: +i.longitude
	});
}

function onTabChange(e) {
	equipmentList.value.length = 0;
	// 重置所有选项
	query.value = {
		page: 1,
		limit: 10
	};
	query.value[e.key] = e.id;
	getData();
}

function handleFilterConfirm(e) {
	equipmentList.value.length = 0;
	query.value = {
		...query.value,
		...e,
		page: 1
	};
	getData();
}

function onClickEquipment(i) {
	// 如果是超级管理员
	if ([0, 1].includes(userStore.userInfo.authorize)) {
		// 如果是待安装
		if (query.value.type == 0) {
			scanQRCode('install', i.host_serial_no);
		}
		// 如果是已安装
		if (query.value.type == 1) {
			uni.navigateTo({
				url: '/pages/equipmentDetails/index?serialNum=' + i.host_serial_no
			});
		}
		// 如果是待巡检
		if (query.value.patrol_state == 1) {
			scanQRCode('patrolInspection', i.host_serial_no);
		}
		// 如果是已巡检
		if (query.value.patrol_state == 2) {
			uni.navigateTo({
				url: './details/index?serialNum=' + i.host_serial_no
			});
		}
	}
	// 如果是设备安装员
	if (userStore.userInfo.authorize == 6) {
		// 未安装
		if (tabCurrent.value === 0) {
			scanQRCode('install', i.host_serial_no);
		}
		// 已安装
		if (tabCurrent.value === 1) {
		}
	}
	// 如果是设备巡检员
	if (userStore.userInfo.authorize == 5) {
		// 未巡检
		if (tabCurrent.value === 0) {
			scanQRCode('patrolInspection', i.host_serial_no);
		}
		// 已巡检
		if (tabCurrent.value === 1) {
			uni.navigateTo({
				url: './details/index?serialNum=' + i.host_serial_no
			});
		}
	}
}

function initQuery() {
	// 如果是巡检员
	if (userStore.userInfo.authorize === 5) query.value.patrol_state = 1;
	// 如果是安装员、超级管理员
	if (userStore.userInfo.authorize === 6 || [0, 1].includes(userStore.userInfo.authorize)) query.value.type = 0;
}

async function getData() {
	uni.showLoading({ title: '数据加载中...', mask: true });
	query.value.page !== 1 && (loadMoreStatus.value = 'loading');
	await fetchEquipmentList(query.value)
		.then((res) => {
			res.data.map((i) => {
				// 如果是设备巡检员
				if (userStore.userInfo.authorize == 5) {
					i.showStatus = true;
					// 未巡检
					if (tabCurrent.value === 0) {
						i.statusText = '待巡检';
						i.statusCode = 'exception';
					}
					// 已巡检
					if (tabCurrent.value === 1) {
						if (i.is_abnormal == 0) {
							i.statusText = '正常';
							i.statusCode = '';
						} else {
							i.statusText = '异常';
							i.statusCode = 'exception';
						}
					}
				}
				// 如果是设备安装员
				if (userStore.userInfo.authorize == 6) {
					// 未安装
					if (tabCurrent.value === 0) {
						i.showStatus = false;
					}
					// 已安装
					if (tabCurrent.value === 1) {
						i.showStatus = true;
						if (i.is_abnormal == 0) {
							i.statusText = '正常';
							i.statusCode = '';
						} else {
							i.statusText = '异常';
							i.statusCode = 'exception';
						}
					}
				}
				// 如果是超级管理员
				if ([0, 1].includes(userStore.userInfo.authorize)) {
					i.showStatus = true;
					// 如果是待安装
					if (query.value.type == 0) {
						i.showStatus = false;
					}
					// 如果是已安装
					if (query.value.type == 1) {
						if (i.is_abnormal == 0) {
							i.statusText = '正常';
							i.statusCode = '';
						} else {
							i.statusText = '异常';
							i.statusCode = 'exception';
						}
					}
					// 如果是待巡检
					if (query.value.patrol_state == 1) {
						i.statusText = '待巡检';
						i.statusCode = 'exception';
					}
					// 如果是已巡检
					if (query.value.patrol_state == 2) {
						if (i.is_abnormal == 0) {
							i.statusText = '正常';
							i.statusCode = '';
						} else {
							i.statusText = '异常';
							i.statusCode = 'exception';
						}
					}
				}
				return i;
			});
			loadMoreStatus.value = res.data?.length === 10 ? 'more' : 'no-more';
			equipmentList.value = query.value.page === 1 ? res.data : [].concat(equipmentList.value, res.data);
			allActions.installer = [
				{
					id: 0,
					name: `未安装(${res.uninstalled_count}台)`,
					key: 'type',
					showStatus: false
				},
				{
					id: 1,
					name: `已安装(${res.installed_count}台)`,
					key: 'type',
					showStatus: true
				}
			];
			allActions.inspector = [
				{
					id: 1,
					name: `待巡检(${res.not_inspected_count}台)`,
					key: 'patrol_state',
					showStatus: true
				},
				{
					id: 2,
					name: `已巡检(${res.inspected_count}台)`,
					key: 'patrol_state',
					showStatus: true
				}
			];
			// 如果是超级管理员
			if ([0, 1].includes(userStore.userInfo.authorize)) {
				tabOptions.value = allActions.superAdmin;
			}
			// 如果是巡检员
			if (userStore.userInfo.authorize === 5) {
				tabOptions.value = allActions.inspector;
			}
			// 如果是安装员
			if (userStore.userInfo.authorize === 6) {
				tabOptions.value = allActions.installer;
			}
		})
		.finally(uni.hideLoading);
}

const keyMap = {
	'01': 'product_identification',
	11: 'production_date',
	17: 'expiry_date',
	21: 'host_serial_no',
	91: 'other'
};

/**
 * @param {'install' | 'patrolInspection'} way
 */
function scanQRCode(way, host_serial_no) {
	uni.scanCode({
		success(res) {
			const { query: querys = '' } = getURLQuery(res.result);
			if (!querys)
				return uni.showModal({
					content: '无效二维码！',
					showCancel: false
				});
			const params = querys.split('(');
			const temp = {};
			for (const param of params) {
				const splitStr = param.split(')');
				const key = splitStr[0];
				if (key in keyMap) temp[keyMap[key]] = splitStr[1];
			}
			console.log(temp)
			if (!temp.host_serial_no)
				return uni.showModal({
					content: '无效二维码！',
					showCancel: false
				});
			if (host_serial_no && host_serial_no !== temp.host_serial_no)
				return uni.showModal({
					content: `${way === 'install' ? '安装' : '巡检'}设备和扫描设备序列号不统一！`,
					showCancel: false
				});
			if(!!temp.other){
				return uni.showModal({
					content: `二维码异常，请重试！`,
					showCancel: false
				});
			}
			//验证设备是否有权限
			valUserDevice({
				host_serial_no:temp.host_serial_no
			}).then(()=>{
				uni.navigateTo({
					url: `/pages/management/${way}/index?serialNum=${temp.host_serial_no}`
				});
			})
			
		}
	});
}
</script>

<style>
.uni-popup.right {
	z-index: -1;
}
</style>
<style scoped lang="scss">
.header {
	position: sticky;
	top: 0;
	z-index: 9;
}
.list {
	display: flow-root;
	.equipment {
		margin: 0 30rpx 30rpx;
		padding: 30rpx;
		border-radius: 16rpx;
		background-color: #fff;
		display: flex;
		column-gap: 20rpx;
		overflow: hidden;
		.cover-image {
			width: 220rpx;
			height: 160rpx;
			flex-shrink: 0;
			border-radius: 8rpx;
		}
		.cont {
			overflow: hidden;
		}
		.serial-number {
			@include ellipsis();
			flex: 1 0 0%;
			margin-right: 20rpx;
		}
		.use-status {
			color: #333;
			font-size: 26rpx;
		}
		.address {
			color: #999;
			font-size: 26rpx;
			align-items: center;
			column-gap: 20rpx;
			.text {
				@include ellipsis(2);
			}
			.nav-icon {
				width: 48rpx;
				height: 48rpx;
				flex-shrink: 0;
			}
		}
	}
	.run-status {
		--color: #55ba63;
		color: var(--color);
		font-size: 26rpx;
		display: flex;
		align-items: center;
		column-gap: 10rpx;
		flex-shrink: 0;
		&.exception {
			--color: #cf4a42;
		}
		&::before {
			content: '';
			display: block;
			width: 16rpx;
			height: 16rpx;
			border-radius: 50%;
			background-color: var(--color);
		}
	}
}
.fixed-bottom {
	position: fixed;
	left: 30rpx;
	right: 30rpx;
	bottom: 30rpx;
}
.no-auth {
	position: absolute;
	top: 50%;
	left: 50%;
	transform: translate(-50%, -50%);
	&__icon {
		width: 466rpx;
		height: 360rpx;
	}
	&__label {
		color: #999;
		font-size: 28rpx;
		text-align: center;
		padding-top: 14rpx;
	}
}
</style>
<style>
page {
	background-color: #f8f8f8;
}
</style>
